package com.cms.admin.action.stuff;

import com.aliyun.oss.model.PutObjectResult;
import com.cms.admin.action.BaseAction;
import com.cms.admin.model.*;
import com.cms.admin.service.common.DepartmentService;
import com.cms.admin.service.common.EntityService;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.stuff.StuffService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.DateUtils;
import com.cms.admin.util.PropertiesService;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by YYY-Work on 2017/4/27.
 */
public class StuffListManagerAction extends BaseAction implements ModelDriven<StuffListExt>{

    private StuffService stuffService;
    private TemplateService templateService;
    private EntityService entityService;
    private DepartmentService departmentListService;

    public List<EntityList> entityLists;
    private List<DepartmentList> departmentLists;

    private StuffListExt search=new StuffListExt();
    private PageBean page;
    private StuffList stuffList;
    private Long stuffID;
    private String replaymessage;


    public String requestStuffList()
    {
        return "success";
    }

    /***
     * 查询医生列表
     */
    public String ajaxQueryStuff()
    {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());

        page = new PageBean(search.getCurrentPage(), search.getPageSize());
        List<StuffListExt> stuffLists=stuffService.selectStuffList(page,search);

        String res = null;

        try {
            res = this.getQueryResult(stuffLists, page);

            JSONObject o = new JSONObject();

            o.put("pageCount", page.getTotalPage());
            o.put("content", res);

            return ajaxJsonSuccessMessage(o);
        }catch (Exception e)
        {
            LOG.error("ajaxQueryStuff",e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    public String ajaxQueryStuffForSelect()
    {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());

        page = new PageBean(search.getCurrentPage(), search.getPageSize());
        List<StuffListExt> stuffLists=stuffService.selectStuffList(page,search);

        String res = null;

        try {
            res = this.getQueryResultForSelect(stuffLists);

            JSONObject o = new JSONObject();

            o.put("pageCount", page.getTotalPage());
            o.put("content", res);

            return ajaxJsonSuccessMessage(o);
        }catch (Exception e)
        {
            LOG.error("ajaxQueryStuff",e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    /**
     * 查询医生详情
     * */
    public String ajaxQueryStuffDetail(){
        initBathPath();
        stuffList=stuffService.queryStuffListById(stuffID);
        List<EntityList> entities=entityService.queryAllEntityList();
        List<DepartmentList> departments=departmentListService.getAllDepartmentList();
        setEntityLists(entities);
        setDepartmentLists(departments);
        return "success";
    }

    
    
    /**
     * 更新医生信息
     * */
    public String ajaxModifyStuff()
    {
        initBathPath();
        if (search.getTypeid()==2)
        {
            search.setTypeName("客服");
            search.setDepartmentid(null);
            search.setStuffTitle(null);
            search.setStuffLabel(null);
            search.setEntityid(2);
        }else
        {
            search.setTypeName("医生");
        }

        if (null!=search.getRegisterWhere())
        {
            StringBuffer registertypeidBF=new StringBuffer();
            if (search.getRegisterWhere().contains("1")||search.getRegisterWhere().contains("2")||search.getRegisterWhere().contains("7"))
            {
                registertypeidBF.append("1,");
            }

            if (search.getRegisterWhere().contains("3"))
            {
                registertypeidBF.append("2,");
            }

            if (search.getRegisterWhere().contains("6"))
            {
                registertypeidBF.append("3,");
            }

            if (search.getRegisterWhere().contains("4"))
            {
                registertypeidBF.append("4,");
            }
            String registertypeid=registertypeidBF.toString();
            if (registertypeid.endsWith(","))
            {
                registertypeid=registertypeid.substring(0,registertypeid.length());
            }
            search.setRegistertypeid(registertypeid);
        }

        /**
         * 上传头像
         * */
        String iconUrl=null;
        if (null!=search.getIcoUrlImage())
        {
            String tgs=null;
            if (search.getEntityid()==2)
            {
                tgs="2";
            }else
            {
                tgs="3";
            }

            try {
                iconUrl=uploadStuffIcon(search.getIcoUrlImage(),tgs,search.getIcoUrlImageFileName());
            }catch (Exception e)
            {
                LOG.error("uploadStuffIcon",e);
            }
            iconUrl=null==iconUrl?"":iconUrl;
            search.setIconUrl(iconUrl);
        }
        search.setUpdateDate(new Date());
        search.setUpdateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
        stuffService.updateStuff(search);
        return "success";
    }

    private String getQueryResult(List<StuffListExt> stuffLists, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("stuffList", stuffLists);
        map.put("page", page);
        map.put("basePath",getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_STUFF_QUERY_RESULT, map);
        return result;
    }

    private String getQueryResultForSelect(List<StuffListExt> stuffLists)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("stuffList", stuffLists);
        map.put("basePath",getBasePath());

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_STUFF_QUERY_FOR_SELECT_RESULT, map);
        return result;
    }
    
	/**
	 * html发布
	 * @return
	 */
	public String publishStuffList()
	{
		StuffListExt example = new StuffListExt();
		example.setStuffid(stuffID);
		List<StuffListExt> list =stuffService.selectStuffList(new PageBean(0,1),example);
		StuffListExt stuff = new StuffListExt();
		if (null ==list||list.size()!=1) {
			replaymessage ="发布失败!";
			return ERROR;
		}else{
			stuff = list.get(0);
		}
		
		ArrayList<String> recommendList = new ArrayList<String>();
		String[] recommeds = stuff.getConsultRecommend().split(",");
		 
		 for (int i = 0; i < recommeds.length; i++) {
			 recommendList.add(recommeds[i]);
		}
		 
		HashMap map = new HashMap();
		map.put("stuffList", stuff);
		map.put("recommendList", recommendList);
		try {
			String htmlUrl = uploadTemplate(templateService, stuff.getStuffid().toString(), map);


			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			replaymessage ="发布失败!";
			e.printStackTrace();
			return ERROR;
		}
		replaymessage ="发布成功!";
		return SUCCESS;
	}
    
	
	public static String uploadTemplate(TemplateService templateService,String srcFileName, Map model) throws Exception
	{
		
		// 获取相对于服务器的根目录
		getRootPath();

		// 开始处理上传文件
 
		//包括了原文件名的路径
		String srcFilePath="";
		
		//未包括目标文件名的路径
		String destPath = "";

		//包括了目标文件名的路径
		String destFilePath = "";
		//后缀
		srcFileName = 2+"-"+srcFileName+".html";
		// 先设置一次目录，后面再做处理
		String savePath = contextPath;
	
		
		//要存储到的目录
		destPath =  savePath +File.separator;
		
		//得到一个随机的文件名
		String uniqueName= srcFileName;
		
		//相对URI
		String DIR =Constants.DOCSHARE_PATH+"/";
		
		destFilePath = destPath+uniqueName;

		File dest = new File(destFilePath);
		
		System.out.println(DIR);

		// 如果目标目录不存在，则创建
		if (!fileExists(destPath)) {
			makeDir(destPath);
		}
		templateService.processCreateHtml(Constants.DOCSHARE_TEMPLATE, model, dest);
		// 从临时目录生成文件到指定文件
		uploadByOssShare( dest, DIR);
		dest.delete();
		
		return DIR+srcFileName;
	}

    private String uploadStuffIcon(File img, String tgs, String fileName)
    {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR="docImage/"+tgs+"/"+System.currentTimeMillis()+tailSuffix;
            PutObjectResult result=uploadByOss(img,DIR);
            if (null!=result)
            {
                return DIR;
            }else
            {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    @Override
    public StuffListExt getModel() {
        return search;
    }


    public StuffService getStuffService() {
        return stuffService;
    }

    public void setStuffService(StuffService stuffService) {
        this.stuffService = stuffService;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public StuffList getStuffList() {
        return stuffList;
    }

    public void setStuffList(StuffList stuffList) {
        this.stuffList = stuffList;
    }

    public Long getStuffID() {

        return stuffID;
    }
    public void setStuffID(Long stuffID) {
        this.stuffID = stuffID;
    }

    public EntityService getEntityService() {
        return entityService;
    }

    public void setEntityService(EntityService entityService) {
        this.entityService = entityService;
    }

    public DepartmentService getDepartmentListService() {
        return departmentListService;
    }

    public void setDepartmentListService(DepartmentService departmentListService) {
        this.departmentListService = departmentListService;
    }

    public List<EntityList> getEntityLists() {
        return entityLists;
    }

    public void setEntityLists(List<EntityList> entityLists) {
        this.entityLists = entityLists;
    }

    public List<DepartmentList> getDepartmentLists() {
        return departmentLists;
    }

    public void setDepartmentLists(List<DepartmentList> departmentLists) {
        this.departmentLists = departmentLists;
    }

	public String getReplaymessage() {
		return replaymessage;
	}

	public void setReplaymessage(String replaymessage) {
		this.replaymessage = replaymessage;
	}
    
    

}
